package com.voxel.sense.infomsg.utils;

import android.content.Context;
import android.content.Intent;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;

import com.example.com.common.utils.FileUtils;
import com.example.com.common.utils.L;

import java.io.File;
import java.io.FileFilter;

import cyy.example.com.facotry.Factory;

public class AppFileUtil {

    public static File getCollectDir() {
        Context context = Factory.app();
        File dir = null;
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            dir = context.getExternalFilesDir("images");
            // In some case, even the sd card is mounted,
            // getExternalCacheDir or getExternalFilesDir will return null
            // may be it is nearly full.
            // we need to construct the folder ourselves
            //有些是因为外存储设备被锁了,然后重启手机,这里就不为null了
            if (dir == null) {
                String imageDir = "/Android/data/" + context.getPackageName() + "/files/collect";
                dir = new File(Environment.getExternalStorageDirectory().getPath() + imageDir);
            }
        } else {
            dir = new File(context.getFilesDir(), "collect");

        }
        if (!dir.exists())
            dir.mkdirs();
        return dir;
    }

    public static File getImageDir() {
        Context context = Factory.app();
        File dir = null;
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            dir = context.getExternalFilesDir("images");
            // In some case, even the sd card is mounted,
            // getExternalCacheDir or getExternalFilesDir will return null
            // may be it is nearly full.
            // we need to construct the folder ourselves
            //有些是因为外存储设备被锁了,然后重启手机,这里就不为null了
            if (dir == null) {
                String imageDir = "/Android/data/" + context.getPackageName() + "/files/images";
                dir = new File(Environment.getExternalStorageDirectory().getPath() + imageDir);
            }
        } else {
            dir = new File(context.getFilesDir(), "images");

        }
        if (!dir.exists())
            dir.mkdirs();
        return dir;
    }

    public static File getAudioDir() {
        Context context = Factory.app();
        File dir = null;
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            dir = context.getExternalFilesDir("audios");
            if (dir == null) {
                String audioDir = "/Android/data/" + context.getPackageName() + "/files/audios";
                dir = new File(Environment.getExternalStorageDirectory().getPath() + audioDir);
            }
        } else {
            dir = new File(context.getFilesDir(), "audios");
        }
        L.d("dir:" + dir);
        if (!dir.exists())
            dir.mkdirs();
        return dir;
    }

    public static File getGiftDir() {
        Context context = Factory.app();
        File dir = null;
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            dir = context.getExternalFilesDir("gift");
            if (dir == null) {
                String avatarDir = "/Android/data/" + context.getPackageName() + "/files/gift";
                dir = new File(Environment.getExternalStorageDirectory().getPath() + avatarDir);
            }
        } else {
            dir = new File(context.getFilesDir(), "gift");

        }
        if (!dir.exists())
            dir.mkdirs();
        return dir;
    }

    public static File getFileDir() {
        Context context = Factory.app();
        File dir = null;
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            dir = context.getExternalFilesDir(null);
            if (dir == null) {
                String fileDir = "/Android/data/" + context.getPackageName() + "/files";
                dir = new File(Environment.getExternalStorageDirectory().getPath() + fileDir);
            }
        } else {
            dir = context.getFilesDir();
        }
        if (!dir.exists())
            dir.mkdirs();
        return dir;
    }

    public static File getCacheDir() {
        Context context = Factory.app();
        File dir = null;
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            dir = context.getExternalCacheDir();
            if (dir == null) {
                String cacheDir = "/Android/data/" + context.getPackageName() + "/cache";
                dir = new File(Environment.getExternalStorageDirectory().getPath() + cacheDir);
            }
        } else {
            dir = context.getCacheDir();
        }
        if (!dir.exists())
            dir.mkdirs();
        return dir;
    }

    //获取地址信息文件
    public static File getAreaFile() {
        File fileDir = getFileDir();
        return new File(fileDir, "area.json");
    }


    //要据文件内容，生成缩略图路径，这样的话同一个文件得到的路径是相同的，那么就不需要重复压缩了
    public static String getThumbnailPath(File file) {
        String ext = FileUtils.getFileExtension(file);
        String md5Name = null;
        md5Name = FileUtils.getFileMD5ToString(file);
        if (TextUtils.isEmpty(md5Name)) {
            md5Name = "" + System.currentTimeMillis();
        }
        return getImageDir() + File.separator + md5Name + "." + ext;
    }

    //将图片保存到手机的功能都存到该目录下
    public static File getPhoneImageDir() {
        File dir = null;
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            String fileDir = "/voxel/app/images";
            dir = new File(Environment.getExternalStorageDirectory().getPath() + fileDir);
        }
        if (dir != null && !dir.exists())//有些手机这里dir可能为null
            dir.mkdirs();
        return dir;
    }

    //
    public static void deleteAllDb() {
        try {
            Context context = Factory.app();
            File databasePath = context.getDatabasePath("123");//这里123随便写个
            File parentFile = databasePath.getParentFile();
            FileUtils.deleteAllFile(parentFile);
        } catch (Throwable e) {

        }
    }

    /**
     * 将图片保存到相册
     */
    public static void notifyMediaStore(File file) {
        Intent borad = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        borad.setData(Uri.fromFile(file));
        Factory.app().sendBroadcast(borad);
    }

    public static void deletePhoto(String path) {
        String url = MediaStore.Images.Media.DATA + "='" + path + "'";
        Factory.app().getContentResolver().delete(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, url, null);
        //通知图库 更新
    }

    /**
     * 通知系统插入新的文件
     *
     * @param path
     */
    public static void updateMediaStore(String path) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            MediaScannerConnection.scanFile(Factory.app(), new String[]{path}, null, new MediaScannerConnection.OnScanCompletedListener() {
                @Override
                public void onScanCompleted(String path, Uri uri) {
                    Intent borad = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                    borad.setData(uri);
                    Factory.app().sendBroadcast(borad);
                }
            });
        }
    }


    /**
     * 扫描qq或微信下载的文件
     */
    public static void MediaStoreScanTencent() {
        //读取QQ在本地的文件夹
        File folder = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Tencent/QQfile_recv/");
        //过滤隐藏文件
        FileFilter filter = new FileFilter() {

            public boolean accept(File pathname) {

                return !pathname.isHidden();//过滤隐藏文件
            }
        };

        File[] listFiles = folder.listFiles(filter);//
        if (listFiles != null && listFiles.length > 0) {
            for (int i = 0; i < listFiles.length; i++) {
                //getAbsolutePath传递文件绝对路径以便同步storage/emulated/0/Tencent/QQfile_recv/***.xlsx
                MediaScannerConnection.scanFile(Factory.app(), new String[]{listFiles[i].getAbsolutePath()}, null,
                        new MediaScannerConnection.OnScanCompletedListener() {
                            public void onScanCompleted(String path, Uri uri) {
                            }
                        });
            }
        }

    }
}
